<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'

const giftList = ref<any[]>([])
const giftForm = reactive({ name: '', iconUrl: '', pricePoints: 0, isActive: true, effectPreset: 'burst' as 'burst'|'fireworks'|'side'|'pride' })
const giftDialog = ref(false)
const uploadingIcon = ref(false)
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''

async function fetchGifts() {
  const { data } = await request.get('/api/admin/gifts')
  giftList.value = data
}

async function createGift() {
  if (!giftForm.name || !giftForm.pricePoints) {
    ElMessage.error('이름과 가격을 입력하세요')
    return
  }
  await request.post('/api/admin/gifts', giftForm)
  ElMessage.success('생성되었습니다')
  giftDialog.value = false
  giftForm.name = ''
  giftForm.iconUrl = ''
  giftForm.pricePoints = 0
  giftForm.isActive = true
  await fetchGifts()
}

async function toggleGift(row: any) {
  await request.put(`/api/admin/gifts/${row.id}`, { isActive: !row.isActive })
  ElMessage.success('업데이트되었습니다')
  await fetchGifts()
}

// 선물 아이콘 업로드
async function uploadGiftIcon(file: File) {
  if (!file.type.startsWith('image/')) {
    ElMessage.error('이미지 파일을 선택하세요')
    return false
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('이미지 크기는 5MB를 초과할 수 없습니다')
    return false
  }

  uploadingIcon.value = true
  try {
    const formData = new FormData()
    formData.append('icon', file)

    const response = await request.post('/api/admin/uploads/gift-icon', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    giftForm.iconUrl = response.data.iconUrl
    ElMessage.success('아이콘 업로드 성공')
    return true
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '아이콘 업로드 실패')
    return false
  } finally {
    uploadingIcon.value = false
  }
}

onMounted(() => {
  fetchGifts()
})
</script>

<template>
  <div class="gift-mgmt">
    <h2 class="title">선물 관리</h2>

    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="giftDialog = true">선물 추가</el-button>
      <el-button :icon="Refresh" @click="fetchGifts">새로고침</el-button>
    </div>

    <el-table :data="giftList" stripe>
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column label="아이콘" width="80" align="center">
        <template #default="{ row }">
          <img
            v-if="row.iconUrl"
            :src="`${API_BASE_URL}${row.iconUrl}`"
            :alt="row.name"
            class="gift-icon"
          />
          <el-text v-else type="info" size="small">아이콘 없음</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="이름" width="160"/>
      <el-table-column prop="pricePoints" label="가격(포인트)" width="140"/>
      <el-table-column prop="effectPreset" label="특수 효과" width="140">
        <template #default="{ row }">
          <el-tag>{{ row.effectPreset || '기본(burst)' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isActive" label="판매 중" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success':'info'">{{ row.isActive ? '예' : '아니오' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="작업" width="160" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="toggleGift(row)">{{ row.isActive ? '판매 중지' : '판매 시작' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="giftDialog" title="선물 추가" width="520px">
      <el-form :model="giftForm" label-width="96px">
        <el-form-item label="이름" required><el-input v-model="giftForm.name" /></el-form-item>

        <el-form-item label="선물 아이콘">
          <div class="icon-upload-area">
            <div v-if="giftForm.iconUrl" class="icon-preview">
              <img
                :src="`${API_BASE_URL}${giftForm.iconUrl}`"
                :alt="giftForm.name"
                class="preview-image"
              />
              <el-button size="small" type="danger" @click="giftForm.iconUrl = ''">삭제</el-button>
            </div>
            <el-upload
              v-else
              :show-file-list="false"
              :before-upload="uploadGiftIcon"
              :disabled="uploadingIcon"
              accept="image/*"
              class="icon-uploader"
            >
              <el-button :loading="uploadingIcon" type="primary">
                {{ uploadingIcon ? '업로드 중...' : '아이콘 선택' }}
              </el-button>
            </el-upload>
            <div class="upload-tip">
              <el-text size="small" type="info">JPG, PNG 형식 지원, 권장 크기 64x64px, 5MB 이하</el-text>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="가격(포인트)" required><el-input v-model.number="giftForm.pricePoints" type="number" /></el-form-item>
        <el-form-item label="표시 효과">
          <el-select v-model="giftForm.effectPreset" style="width: 240px">
            <el-option label="색종이 폭발(burst)" value="burst" />
            <el-option label="불꽃놀이(fireworks)" value="fireworks" />
            <el-option label="양쪽 포탄(side)" value="side" />
            <el-option label="축제(pride)" value="pride" />
          </el-select>
        </el-form-item>
        <el-form-item label="판매 여부"><el-switch v-model="giftForm.isActive" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="giftDialog=false">취소</el-button>
        <el-button type="primary" @click="createGift">저장</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.gift-mgmt{padding:16px}
.title{margin:0 0 12px}
.toolbar{display:flex;gap:8px;margin:10px 0}

/* 테이블의 선물 아이콘 */
.gift-icon {
  width: 32px;
  height: 32px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
}

/* 아이콘 업로드 영역 */
.icon-upload-area {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.icon-preview {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background: var(--el-bg-color-page);
}

.preview-image {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
}

.icon-uploader {
  display: inline-block;
}

.upload-tip {
  margin-top: 4px;
}
</style>

